import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/helloThymeleaf")
public class HelloThymeleafServlet extends HttpServlet {
    //这是Thymeleaf中最核心的类 TemplateEngine模板引擎
    private TemplateEngine engine = new TemplateEngine();

    @Override
    public void init() throws ServletException {
        //创建一个模板解析器对象,搭配上下文来使用
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(this.getServletContext());
        //让模板解析器来加载模板文件，这里的前缀就表示模板文件所在的目录，正因为如此，模板文件就必须放在WEB-INF中
        //设置前缀后缀，让模板引擎知道要加载哪些文件到内存中，以备后用
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");
        //把解析器对象，设置到engine中
        engine.setTemplateResolver(resolver);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //初始化之后，就要执行模板渲染了
        //1.先从参数中读取出用户要传过来的message的值
        String message = req.getParameter("message");
        //2.把当前请求中读取出来的message的值和模板中的${message}关联起来
        WebContext webContext = new WebContext(req,resp,this.getServletContext());
        webContext.setVariable("message",message);
        //3.进行最终渲染,将webContext的内容替换到hello
        String html = engine.process("hello",webContext);
        System.out.println(html);
        resp.getWriter().write(html);
    }
}
